package service.impl;

import dao.UserDao;
import entity.User;
import exception.RequestParameterErrorException;
import exception.UserExistException;
import exception.UserNotExistException;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import service.UserService;
import util.ParameterUtil;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/5/19 14:53
 * Version:1.0-SNAPSHOT
 * Description:
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        User user = userDao.selectByUsernameAndPassword(username,password);
        if(null == user){
            throw new UserNotExistException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(phone) || ParameterUtil.isNull(address)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        User selectUser = userDao.selectByUsername(username);
        if(selectUser != null){
            throw new UserExistException("该用户已经被注册");
        }
        User user = new User(username,password,phone,address);

        userDao.insertUser(user);
    }
}
